<template>
  <view class="employee-statistics" v-if="permissionChecked && hasPermission">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <uni-icons type="spinner-cycle" size="24" color="#667eea"></uni-icons>
      <text class="loading-text">加载员工数据中...</text>
    </view>

    <!-- 错误状态 -->
    <view v-else-if="error" class="error-container">
      <uni-icons type="closeempty" size="32" color="#ff6b6b"></uni-icons>
      <text class="error-text">{{ error }}</text>
      <view class="retry-button" @click="handleRetry">
        <text>重试</text>
      </view>
    </view>

    <!-- 数据展示 -->
    <view v-else class="statistics-content">
      <!-- 标题 -->
      <view class="section-title">
        <view class="title-icon">
          <uni-icons type="person" size="18" color="#7881de"></uni-icons>
        </view>
        <text class="title-text">员工数据统计</text>
      </view>

      <!-- 手风琴面板 -->
      <view class="accordion-container">
        <!-- 员工数据面板 -->
        <view class="accordion-panel">
          <view
            class="panel-header"
            @click="togglePanel('employeeData')"
            :class="{ 'panel-header-active': activePanel === 'employeeData' }"
          >
            <view class="panel-title">
              <uni-icons
                type="person-filled"
                size="18"
                color="#667eea"
              ></uni-icons>
              <text class="panel-title-text">员工数据</text>
            </view>
            <uni-icons
              :type="activePanel === 'employeeData' ? 'up' : 'down'"
              size="16"
              color="#666"
              class="panel-arrow"
            ></uni-icons>
          </view>
          <view
            class="panel-content"
            :class="{
              'panel-content-expanded': activePanel === 'employeeData',
            }"
          >
            <view class="status-cards">
              <DataCard
                v-for="(item, index) in statusCardsData"
                :key="index"
                :value="item.value"
                :label="item.label"
                :icon="item.icon"
                :theme="item.theme"
                :clickable="true"
                @click="handleStatusCardClick(item)"
              />
            </view>
          </view>
        </view>

        <!-- 员工年龄分布面板 -->
        <view class="accordion-panel">
          <view
            class="panel-header"
            @click="togglePanel('ageDistribution')"
            :class="{
              'panel-header-active': activePanel === 'ageDistribution',
            }"
          >
            <view class="panel-title">
              <uni-icons type="calendar" size="18" color="#667eea"></uni-icons>
              <text class="panel-title-text">员工年龄分布</text>
            </view>
            <uni-icons
              :type="activePanel === 'ageDistribution' ? 'up' : 'down'"
              size="16"
              color="#666"
              class="panel-arrow"
            ></uni-icons>
          </view>
          <view
            class="panel-content"
            :class="{
              'panel-content-expanded': activePanel === 'ageDistribution',
            }"
          >
            <view class="chart-container">
              <PieChart
                :data="ageDistributionData"
                title="员工年龄分布"
                :size="180"
                :colors="[
                  '#FF6B6B',
                  '#4ECDC4',
                  '#45B7D1',
                  '#96CEB4',
                  '#FFEAA7',
                ]"
                center-label="总人数"
              />
            </view>
          </view>
        </view>

        <!-- 员工性别分布面板 -->
        <view class="accordion-panel">
          <view
            class="panel-header"
            @click="togglePanel('genderDistribution')"
            :class="{
              'panel-header-active': activePanel === 'genderDistribution',
            }"
          >
            <view class="panel-title">
              <uni-icons type="person" size="18" color="#667eea"></uni-icons>
              <text class="panel-title-text">员工性别分布</text>
            </view>
            <uni-icons
              :type="activePanel === 'genderDistribution' ? 'up' : 'down'"
              size="16"
              color="#666"
              class="panel-arrow"
            ></uni-icons>
          </view>
          <view
            class="panel-content"
            :class="{
              'panel-content-expanded': activePanel === 'genderDistribution',
            }"
          >
            <view class="chart-container">
              <PieChart
                :data="genderDistributionData"
                title="员工性别分布"
                :size="180"
                :colors="['#FF6B6B', '#4ECDC4', '#DDD']"
                center-label="总人数"
              />
            </view>
          </view>
        </view>

        <!-- 在职状态分布面板 -->
        <view class="accordion-panel">
          <view
            class="panel-header"
            @click="togglePanel('workStatusDistribution')"
            :class="{
              'panel-header-active': activePanel === 'workStatusDistribution',
            }"
          >
            <view class="panel-title">
              <uni-icons
                type="checkmarkempty"
                size="18"
                color="#667eea"
              ></uni-icons>
              <text class="panel-title-text">在职状态分布</text>
            </view>
            <uni-icons
              :type="activePanel === 'workStatusDistribution' ? 'up' : 'down'"
              size="16"
              color="#666"
              class="panel-arrow"
            ></uni-icons>
          </view>
          <view
            class="panel-content"
            :class="{
              'panel-content-expanded':
                activePanel === 'workStatusDistribution',
            }"
          >
            <view class="chart-container">
              <PieChart
                :data="workStatusDistributionData"
                title="在职状态分布"
                :size="180"
                :colors="['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4']"
                center-label="总人数"
              />
            </view>
          </view>
        </view>

        <!-- 最高学历分布面板 -->
        <view class="accordion-panel">
          <view
            class="panel-header"
            @click="togglePanel('educationDistribution')"
            :class="{
              'panel-header-active': activePanel === 'educationDistribution',
            }"
          >
            <view class="panel-title">
              <uni-icons type="star" size="18" color="#667eea"></uni-icons>
              <text class="panel-title-text">最高学历分布</text>
            </view>
            <uni-icons
              :type="activePanel === 'educationDistribution' ? 'up' : 'down'"
              size="16"
              color="#666"
              class="panel-arrow"
            ></uni-icons>
          </view>
          <view
            class="panel-content"
            :class="{
              'panel-content-expanded': activePanel === 'educationDistribution',
            }"
          >
            <view class="chart-container">
              <PieChart
                :data="educationDistributionData"
                title="最高学历分布"
                :size="180"
                :colors="[
                  '#FF6B6B',
                  '#4ECDC4',
                  '#45B7D1',
                  '#96CEB4',
                  '#FFEAA7',
                ]"
                center-label="总人数"
              />
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from "vue";
import DataCard from "./charts/DataCard.vue";
import PieChart from "./charts/PieChart.vue";
import type { EmployeeStatistics } from "../pages/work/api/interface";
import { auth } from "../utils/authFunction";

interface Props {
  data?: EmployeeStatistics | null;
  loading?: boolean;
  error?: string | null;
}

const props = withDefaults(defineProps<Props>(), {
  data: null,
  loading: false,
  error: null,
});

const emit = defineEmits<{
  retry: [];
  statusCardClick: [type: string, value: number];
}>();

// 手风琴面板展开状态 - 单选模式，只保留一个展开的面板
const activePanel = ref<string>("employeeData"); // 默认展开员工数据面板

// 权限控制
const hasPermission = ref<boolean>(false);
const permissionChecked = ref<boolean>(false);

// 模拟数据（当没有传入数据时使用）
const mockData: EmployeeStatistics = {
  statusStats: {
    在职员工数量: 2096,
    待入职员工数量: 0,
    待离职员工数量: 0,
    待退休员工数量: 69,
    试用期员工数量: 0,
  },
  detailStats: {
    员工年龄分布: {
      "18-29": 300,
      "30-39": 833,
      "40-49": 581,
      "50-59": 350,
      "60+": 26,
    },
    员工性别分布: {
      男: 1508,
      女: 588,
      未知: 0,
    },
    在职状态分布: {
      试用期: 0,
      在职: 2096,
      离职: 341,
      退休: 0,
    },
    最高学历分布: {
      初中及以下: 215,
      "高中/中专": 658,
      大专: 880,
      本科: 331,
      硕士及以上: 4,
    },
  },
};

// 使用传入的数据或模拟数据
const currentData = computed(() => props.data || mockData);

// 状态卡片数据
const statusCardsData = computed(() => {
  const stats = currentData.value.statusStats;
  return [
    {
      label: "在职员工",
      value: stats.在职员工数量,
      icon: "person-filled",
      theme: "success" as const,
      type: "active",
    },
    {
      label: "待入职员工",
      value: stats.待入职员工数量,
      icon: "plus-filled",
      theme: "info" as const,
      type: "pending",
    },
    {
      label: "待离职员工",
      value: stats.待离职员工数量,
      icon: "minus-filled",
      theme: "warning" as const,
      type: "leaving",
    },
    {
      label: "待退休员工",
      value: stats.待退休员工数量,
      icon: "star",
      theme: "primary" as const,
      type: "retiring",
    },
    {
      label: "试用期员工",
      value: stats.试用期员工数量,
      icon: "calendar",
      theme: "danger" as const,
      type: "probation",
    },
  ];
});

// 年龄分布数据
const ageDistributionData = computed(() => {
  const ageData = currentData.value.detailStats.员工年龄分布;
  return Object.entries(ageData).map(([label, value]) => ({
    label,
    value,
  }));
});

// 性别分布数据
const genderDistributionData = computed(() => {
  const genderData = currentData.value.detailStats.员工性别分布;
  return Object.entries(genderData).map(([label, value]) => ({
    label,
    value,
  }));
});

// 学历分布数据
const educationDistributionData = computed(() => {
  const educationData = currentData.value.detailStats.最高学历分布;
  return Object.entries(educationData).map(([label, value]) => ({
    label,
    value,
  }));
});

// 在职状态分布数据
const workStatusDistributionData = computed(() => {
  const statusData = currentData.value.detailStats.在职状态分布;
  return Object.entries(statusData).map(([label, value]) => ({
    label,
    value,
  }));
});

// 处理重试
const handleRetry = () => {
  emit("retry");
};

// 切换面板展开/收起状态 - 单选模式
const togglePanel = (panelKey: string) => {
  // 如果点击的是当前激活的面板，则收起它
  if (activePanel.value === panelKey) {
    activePanel.value = "";
  } else {
    // 否则激活点击的面板（自动收起其他面板）
    activePanel.value = panelKey;
  }
};

// 权限检查函数
const checkPermission = () => {
  try {
    // 检查用户是否具有 /api/sysperson/search 接口的访问权限
    hasPermission.value = auth("/api/sysperson/search");
    console.log("员工数据统计权限检查结果:", hasPermission.value);
  } catch (error) {
    console.error("权限检查失败:", error);
    hasPermission.value = false;
  } finally {
    permissionChecked.value = true;
  }
};

// 处理状态卡片点击
const handleStatusCardClick = (item: any) => {
  emit("statusCardClick", item.type, item.value);
};

// 组件挂载时检查权限
onMounted(() => {
  checkPermission();
});
</script>

<style lang="scss" scoped>
.employee-statistics {
  width: 100%;

  .loading-container,
  .error-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 20px;
    gap: 12px;

    .loading-text,
    .error-text {
      color: #666;
      font-size: 14px;
      text-align: center;
    }

    .error-desc {
      color: #999;
      font-size: 12px;
      text-align: center;
    }

    .retry-button {
      background: #667eea;
      color: #ffffff;
      padding: 8px 16px;
      border-radius: 8px;
      font-size: 14px;
      cursor: pointer;
      transition: all 0.3s ease;

      &:active {
        transform: scale(0.95);
      }
    }
  }

  .statistics-content {
    .section-title {
      display: flex;
      align-items: center;
      margin-bottom: 16px;
      gap: 8px;

      .title-icon {
        width: 32px;
        height: 32px;
        border-radius: 8px;
        background: rgba(120, 129, 222, 0.1);
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .title-text {
        color: #1a1a1a;
        font-size: 16px;
        font-weight: 600;
        flex: 1;
      }
    }

    .accordion-container {
      .accordion-panel {
        background: #ffffff;
        border-radius: 16px;
        margin-bottom: 16px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
        overflow: hidden;
        transition: all 0.3s ease;

        &:hover {
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .panel-header {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 20px;
          cursor: pointer;
          transition: all 0.3s ease;
          border-bottom: 1px solid transparent;

          &:hover {
            background: #f8f9fa;
          }

          &.panel-header-active {
            background: #f0f4ff;
            border-bottom-color: #e6f0ff;
          }

          .panel-title {
            display: flex;
            align-items: center;
            gap: 12px;

            .panel-title-text {
              font-size: 16px;
              font-weight: 600;
              color: #1a1a1a;
            }
          }

          .panel-arrow {
            transition: transform 0.3s ease;
          }
        }

        .panel-content {
          max-height: 0;
          overflow: hidden;
          transition:
            max-height 0.3s ease,
            padding 0.3s ease;

          &.panel-content-expanded {
            max-height: 1000px;
            padding: 0 16px 16px 16px;
          }

          .status-cards {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 12px;
          }

          .chart-container {
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 12px 0;
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .employee-statistics {
    .statistics-content {
      .accordion-container {
        .accordion-panel {
          margin-bottom: 12px;

          .panel-header {
            padding: 10px;

            .panel-title {
              gap: 8px;

              .panel-title-text {
                font-size: 14px;
              }
            }
          }

          .panel-content {
            &.panel-content-expanded {
              padding: 0 12px 12px 12px;
            }

            .status-cards {
              grid-template-columns: repeat(2, 1fr);
              gap: 10px;
            }

            .chart-container {
              padding: 10px 0;
            }
          }
        }
      }
    }
  }
}

@media (max-width: 600px) {
  .employee-statistics {
    .statistics-content {
      .accordion-container {
        .accordion-panel {
          .panel-content {
            .status-cards {
              grid-template-columns: repeat(2, 1fr);
              gap: 8px;
            }
          }
        }
      }
    }
  }
}
</style>
